package com.syg.validation.controller;

import com.syg.validation.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.groups.Default;
import java.util.Set;

@RestController
public class ValidationController {

    @Autowired
    private javax.validation.Validator globalValidator;

    @PostMapping("/valida")
    public String validation(@RequestBody User user) {
        Set<ConstraintViolation<User>> validate = globalValidator.validate(user, Default.class);
        // 如果校验通过，validate为空；否则，validate包含未校验通过项
        if (validate.isEmpty()) {
            // 校验通过，才会执行业务逻辑处理
            System.out.println("校验通过，才会执行业务逻辑处理");

        } else {
            for (ConstraintViolation<User> userDTOConstraintViolation : validate) {
                // 校验失败，做其它逻辑
                System.out.println(userDTOConstraintViolation);
            }
        }
        return "";
    }
}
